<?php

/**
 * ECSHOP 淘宝商品管理程序
 * ============================================================================
 * 版权所有 2005-2009 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: goods.php 16881 2009-12-14 09:19:16Z liubo $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
include_once(ROOT_PATH . 'includes/lib_taoapi.php');

$exc = new exchange($ecs->table('item'), $db, 'num_iid', 'title');

/*------------------------------------------------------ */
//-- 商品列表，商品回收站
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'list')
{
    admin_priv('item_manage');

    $cat_id = empty($_REQUEST['cat_id']) ? 0 : intval($_REQUEST['cat_id']);    $suppliers_id = isset($_REQUEST['suppliers_id']) ? (empty($_REQUEST['suppliers_id']) ? '' : trim($_REQUEST['suppliers_id'])) : '';
    $is_on_sale = isset($_REQUEST['is_on_sale']) ? ((empty($_REQUEST['is_on_sale']) && $_REQUEST['is_on_sale'] === 0) ? '' : trim($_REQUEST['is_on_sale'])) : '';


    /* 模板赋值 */
    $smarty->assign('ur_here', $_LANG['07_item_list']);

    $action_link = array('href' => 'item.php?act=add', 'text' => $_LANG['07_item_add']);
    $smarty->assign('action_link',  $action_link);
    $smarty->assign('cat_list',     cat_list(0, $cat_id));
    $smarty->assign('lang',         $_LANG);

    $item_list = item_list();
    $smarty->assign('item_list',   $item_list['items']);
    $smarty->assign('filter',       $item_list['filter']);
    $smarty->assign('record_count', $item_list['record_count']);
    $smarty->assign('page_count',   $item_list['page_count']);
    $smarty->assign('full_page',    1);

    /* 排序标记 */
    $sort_flag  = sort_flag($item_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    /* 显示商品列表页面 */
    assign_query_info();
    $smarty->display('item_list.htm');
}
/*------------------------------------------------------ */
//-- 转化为ecshop商品
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_is_convert')
{
    check_authz_json('item_manage');

    $num_iid       = $_POST['id'];
    $is_convert    = intval($_POST['val']);

    $sql = "SELECT cat_id, num_iid, title, num, price, `desc`, pic_url, list_time FROM ".$ecs->table('item')." WHERE num_iid = '$num_iid'";
    $query = $db->query($sql);
    if($item = $db->fetch_array($query)){ extract($item); }
    /* 检查是否重复 */
    $count = $db->getOne("SELECT COUNT(goods_id) FROM ".$ecs->table('goods')." WHERE goods_sn = '$num_iid'");
    if ($count)
    {
	    	$db->query("UPDATE ".$ecs->table('goods')." SET cat_id='$cat_id', goods_name='$title', goods_number='$num', shop_price='$price', goods_desc='$desc', goods_thumb='$pic_url', goods_img='$pic_url', add_time='$list_time' WHERE goods_sn='$num_iid'");
    }else{
	    	$db->query("INSERT INTO ".$ecs->table('goods')."(cat_id, goods_sn, goods_name, goods_number, shop_price, goods_desc, goods_thumb, goods_img, add_time)".
	    		" VALUES('$cat_id', '$num_iid', '$title', '$num', '$price', '$desc', '$pic_url', '$pic_url', '$list_time')");
    }
	$db->query("UPDATE ".$ecs->table('item')." SET is_convert = '1' where num_iid = '$num_iid'");
	clear_cache_files();
	make_json_result($is_convert);
}

/*------------------------------------------------------ */
//-- 批量操作
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'batch')
{
    /* 取得要操作的商品编号 */
    $num_iid = !empty($_POST['checkboxes']) ? join(',', $_POST['checkboxes']) : 0;
    
    $query = $db->query("SELECT iid FROM ".$ecs->table('item')." WHERE num_iid " . db_create_in($num_iid));
    while($row = $db->fetch_array($query)){
    	$iids[] = $row['iid'];
    }
    $iid = !empty($iids) ? join(',', $iids) : 0;

    if (isset($_POST['type']))
    {
        /* 删除 */
        if ($_POST['type'] == 'trash')
        {
            $sql = "DELETE FROM " . $ecs->table('item') .
                "WHERE num_iid " . db_create_in($num_iid);

	        $db->query($sql);
        }
        /* 转移到分类 */
        elseif ($_POST['type'] == 'move_to')
        {
            $sql = "UPDATE " . $ecs->table('item') .
                " SET cat_id = '$_POST[target_cat]'" .
                "WHERE num_iid " . db_create_in($num_iid);

        	$db->query($sql);
        }
        /* 还原 */
        elseif ($_POST['type'] == 'update')
        {
			$url = 'item.php?act=edit&num_iid='.$num_iid;

			ecs_header("Location: $url\n");
			exit;
        }
    }

    /* 清除缓存 */
    clear_cache_files();

    $link[] = array('href' => 'item.php?act=list', 'text' => $_LANG['07_item_list']);
    sys_msg($_LANG['batch_handle_ok'], 0, $link);
}
/*------------------------------------------------------ */
//-- 排序、分页、查询
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query')
{
    $item_list = item_list();

    $smarty->assign('item_list',   $item_list['items']);
    $smarty->assign('filter',       $item_list['filter']);
    $smarty->assign('record_count', $item_list['record_count']);
    $smarty->assign('page_count',   $item_list['page_count']);

    /* 排序标记 */
    $sort_flag  = sort_flag($item_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    make_json_result($smarty->fetch('item_list.htm'), '',
        array('filter' => $item_list['filter'], 'page_count' => $item_list['page_count']));
}

/*------------------------------------------------------ */
//-- 放入回收站
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'remove')
{
    $num_iid = $_REQUEST['id'];
	if ($num_iid < 0)
    {
        make_json_error('invalid params');
    }

    /* 删除商品 */
    $exc->drop($num_iid);
    
    $url = 'item.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    ecs_header("Location: $url\n");
    exit;

}

/*------------------------------------------------------ */
//-- 添加淘宝商品
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add')
{
	$action_link = array('href' => 'item.php?act=list', 'text' => $_LANG['item_list']);
    $smarty->assign('action_link',  $action_link);
	$smarty->assign('form_action', 'insert');

    /* 显示商品信息页面 */
    assign_query_info();
    $smarty->display('item_info.htm');

}

/*------------------------------------------------------ */
//-- 添加淘宝商品
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit')
{
	$action_link = array('href' => 'item.php?act=list', 'text' => $_LANG['item_list']);
    $smarty->assign('action_link',  $action_link);
    $smarty->assign('num_iid',  $_REQUEST['num_iid']);
	$smarty->assign('form_action', 'save');

    /* 显示商品信息页面 */
    assign_query_info();
    $smarty->display('item_info.htm');

}

/*------------------------------------------------------ */
//-- 添加淘宝商品进行插入操作
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'insert' or $_REQUEST['act'] == 'save')
{
	/*提取淘宝客商品信息*/
	$num_iid = str_replace(chr(13).chr(10), ",", $_REQUEST['num_iid']);
	$iids = '';
	
	$items = taobao_taobaoke_items_detail_get_num($num_iid);
	$count = $items['total_results'];
	if($count <= 1){
		$item_list[] = $items['taobaoke_item_details']['taobaoke_item_detail'];
	}else{
		$item_list = $items['taobaoke_item_details']['taobaoke_item_detail'];
	}
	
	foreach ($item_list as $key => $item_tmp){
		$click_url=$item_tmp['click_url'];
		$item = $item_tmp['item'];
		
		$detail_url=$item['detail_url'];
		$num=$item['num'];
		$list_time=$item['list_time'];
		$delist_time=$item['delist_time'];
		$num_iid=$item['num_iid'];
		$iid=$item['iid'];
		$desc=$item['desc'];
		$cid=$item['cid'];
		$title=$item['title'];
		$nick=$item['nick'];
		$num_iid=$item['num_iid'];
		$type=$item['type'];
		$pic_url=$item['pic_url'];
		$price=$item['price'];
		$post_fee=$item['post_fee'];
		$volume=empty($item['volume'])?0:$item['volume'];
		
		if($key == 0)$iids = "$iid";
		else $iids .= ",$iid";
		
		$item_num = $db->getOne("SELECT COUNT(iid) FROM ".$ecs->table('item')." where iid = '$iid'");
		if($item_num <= 0){
			$sql = "INSERT INTO ".$ecs->table('item')."(iid,click_url,detail_url,num,list_time,delist_time,
					cat_id,title,nick,num_iid,type,pic_url,price,post_fee,volume,last_update) 
				VALUES('$iid','$click_url','$detail_url','$num','$list_time','$delist_time','$cid','$title','$nick',
					'$num_iid','$type','$pic_url','$price','$post_fee','$volume','".gmtime()."')";
		}else{
			$sql = "UPDATE ".$ecs->table('item')." SET iid='$iid',click_url='$click_url',detail_url='$detail_url',num='$num',
				list_time='$list_time',delist_time='$delist_time',cat_id='$cid',title='$title',nick='$nick',num_iid='$num_iid',
				type='$type',pic_url='$pic_url',price='$price',post_fee='$post_fee',volume='$volume',last_update='".gmtime()."'
				where iid = '$iid'";
		}

		$db->query($sql);
	}

	/*转化淘宝客数据*/
	$item_list = array();
	$items = taobao_taobaoke_items_convert($iids);
	if($count <=1){
		$item_list[] = $items;
	}else $item_list = $items;
	
	foreach ($item_list as $item){
		$commission=$item['commission'];
		$commission_num=$item['commission_num'];
		$commission_rate=$item['commission_rate']; 
		$commission_volume=$item['commission_volume'];
		$item_location=$item['item_location'];
		$click_url=$item['click_url'];
		$iid=$item['iid'];
		
		$sql = "UPDATE ".$ecs->table('item')." SET item_location='$item_location',commission='$commission',commission_num='$commission_num',commission_rate='$commission_rate',commission_volume='$commission_volume' WHERE iid = '$iid'";

		$db->query($sql);
	}

	/* 清除缓存 */
    clear_cache_files();

    $link[0]['text'] = $_LANG['continue_add'];
    $link[0]['href'] = 'item.php?act=add';

    $link[1]['text'] = $_LANG['back_list'];
    $link[1]['href'] = 'item.php?act=list';

    sys_msg($_LANG['itemadd_succed'], 0, $link);
}

/**
 * 获得商品列表
 *
 * @access  public
 * @params  integer $isdelete
 * @params  integer $real_goods
 * @params  integer $conditions
 * @return  array
 */
function item_list($conditions = '')
{
    $filter['cat_id']           = empty($_REQUEST['cat_id']) ? 0 : intval($_REQUEST['cat_id']);
    $filter['nick']       = empty($_REQUEST['nick']) ? '' : trim($_REQUEST['nick']);
    $filter['is_convert']       = !isset($_REQUEST['is_convert']) ? '' : $_REQUEST['is_convert'];
    $filter['commission']       = !isset($_REQUEST['commission']) ? '' : $_REQUEST['commission'];
    if (isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax'] == 1)
    {
        $filter['keyword'] = json_str_iconv($_REQUEST['keyword']);
    }
    $filter['sort_by']          = empty($_REQUEST['sort_by']) ? 'last_update' : trim($_REQUEST['sort_by']);
    $filter['sort_order']       = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
    $filter['is_delete']        = $is_delete;

    $where = $filter['cat_id'] > 0 ? " AND " . get_children($filter['cat_id']) : '';
	
    /* 关键字 */
    if (!empty($filter['keyword']))
    {
        $where .= " AND title LIKE '%" . mysql_like_quote($filter['keyword']) . "%'";
    }

    /* 关键字 */
    if (!empty($filter['nick']))
    {
        $where .= " AND nick LIKE '%" . mysql_like_quote($filter['nick']) . "%'";
    }
    /* 关键字 */
    if ($filter['is_convert'] != "")
    {
        $where .= " AND is_convert = '" . $filter['is_convert'] . "'";
    }
    /* 佣金 */
    if ($filter['commission'] != "")
    {
		if($filter['commission'] == 0)$where .= " AND commission <= '0'";
		else $where .= " AND commission > '0'";
    }
    
    $where .= $conditions;
	
    /* 记录总数 */
    $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('item'). " AS i WHERE 1 $where";
    $filter['record_count'] = $GLOBALS['db']->getOne($sql);

    /* 分页大小 */
    $filter = page_and_size($filter);

    $sql = "SELECT num_iid, iid, title, nick, detail_url, click_url, cat_id, pic_url, num, list_time, delist_time, " .
                " price, volume, commission, commission_rate, commission_num, commission_volume, is_convert, last_update ".
                " FROM " . $GLOBALS['ecs']->table('item') . " AS i WHERE 1 $where" .
                " ORDER BY $filter[sort_by] $filter[sort_order] ".
                " LIMIT " . $filter['start'] . ",$filter[page_size]";

    $filter['keyword'] = stripslashes($filter['keyword']);

    $row = $GLOBALS['db']->getAll($sql);
	
	if(is_array($row))
	foreach($row as $key => $r){
		$row[$key]['last_update'] = date("Y-m-d", $r['last_update']);
	}

    return array('items' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}
?>